﻿using Microsoft.AspNetCore.Mvc;
using PARK.CardAcct.Entitys;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumMachineCardtype;
using PARK.Consumer.Interfaces;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace PARK.Consumer
{
    /// <summary>
    /// 消费机可用卡类型
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "MachineCardtype", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumMachineCardtypeService : IConsumMachineService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ConsumMachineCardtypeEntity> _consumMachineCardtypeRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ConsumMachineCardtypeService"/>类型的新实例
        /// </summary>
        public ConsumMachineCardtypeService(
            ISqlSugarRepository<ConsumMachineCardtypeEntity> consumMachineCardtypeRepository,
            IUserManager userManager)
        {
            _consumMachineCardtypeRepository = consumMachineCardtypeRepository;
            _db = _consumMachineCardtypeRepository.Context;
            _userManager = userManager;
        }

        #region Get
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ConsumMachineCardtypeEntity>().FirstAsync(p => p.Id == id);
            return entity;
        }
        /// <summary>
		/// 获取列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ConsumMachineCardtypeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "MachineName,CardTypeName" : input.sidx;
                var data = await _consumMachineCardtypeRepository.Context.Queryable<ConsumMachineCardtypeEntity, ConsumMachineEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.MachineId == a.MachineId))
                //公司权限
                .Where((a, b) => a.CompanyId.Equals(userInfo.companyId))                
                .WhereIF(!string.IsNullOrEmpty(input.merchantId), (a, b) => b.MerchantId.Equals(input.merchantId))
                .WhereIF(!string.IsNullOrEmpty(input.machineId), (a, b) => a.MachineId.Equals(input.machineId))
                .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), (a, b) => a.CardTypeId.Contains(input.cardTypeId))
                .Select((a, b) => new ConsumMachineCardtypeListOutput
                {
                    Id = a.Id,
                    MachineId = a.MachineId,
                    MachineNo = a.MachineNo,
                    MachineName = a.MachineName,
                    MachineSerialNum = a.MachineSerialNum,
                    CardTypeId = a.CardTypeId,
                    CardTypeName = a.CardTypeName,
                    Description = a.Description,
                    CreatorUserId = a.CreatorUserId,
                    CreatorUserName = a.CreatorUserName,
                    CreatorTime = a.CreatorTime,
                    CompanyId = a.CompanyId,
                    CompanyName = a.CompanyName,
                    MerchantId = b.MerchantId,
                    MerchantName =b.MerchantName
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<ConsumMachineCardtypeListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<ConsumMachineCardtypeEntity>().FirstAsync(p => p.Id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                var isOk = await _db.Deleteable(entity).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 获取指定消费机已经分配卡类型
        /// <summary>
        /// 获取指定消费机已经分配卡类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetCardtypeByMachId")]
        public async Task<dynamic> GetCardtypeByMachId(string MachineId)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (string.IsNullOrEmpty(MachineId))
            {
                MachineId = "''";
            }
            var data = await _db.Queryable<ConsumMachineCardtypeEntity>()
                //公司权限
                .Where(p => p.CompanyId.Equals(userInfo.companyId) && p.MachineId.Equals(MachineId))
                .Select(it => new MachineCardtypeTransferListOutput
                {
                    CardTypeId = it.CardTypeId,
                    CardTypeName = it.CardTypeName
                }).MergeTable().ToListAsync();
            return data;
        }
        #endregion

        #region 维护消费机可用卡片
        /// <summary>
        /// 维护消费机可用卡片
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] MachineCardtypeCrBatchInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                try
                {
                    var MachineEntity = new ConsumMachineEntity();
                    if (string.IsNullOrEmpty(input.machineId))
                    {
                        throw PARKException.Bah("请选择消费机");
                    }
                    else
                    {
                         MachineEntity = await _db.Queryable<ConsumMachineEntity>().FirstAsync(p => p.MachineId == input.machineId);
                    }

                    List<ConsumMachineCardtypeEntity> machineCardtypeList = new List<ConsumMachineCardtypeEntity>();
                    if (input.addcardtypeList != null && input.addcardtypeList.Count > 0)
                    {
                        #region 处理需要分配卡类型
                        foreach (var item in input.addcardtypeList)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                var Entity = new ConsumMachineCardtypeEntity();
                                Entity.CardTypeId = item;
                                //获取卡类型
                                var Cardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == item);
                                if (Cardtype != null)
                                {
                                    Entity.CardTypeName = Cardtype.CardTypeName;
                                }
                                Entity.MachineId = input.machineId;
                                Entity.MachineNo = MachineEntity.MachineNo;
                                Entity.MachineName = MachineEntity.MachineName;
                                Entity.MachineSerialNum = MachineEntity.MachineSerialNum;
                                Entity.CompanyId = userInfo.companyId;
                                Entity.CompanyName = userInfo.companyName;
                                Entity.Create();
                                machineCardtypeList.Add(Entity);
                            }
                        }
                        #endregion
                    }
                    if (machineCardtypeList != null && machineCardtypeList.Count > 0)
                    {
                        //开启事务
                        _db.BeginTran();
                        //删除原类型
                        var Paras = new List<SugarParameter>();
                        StringBuilder dbSql = new StringBuilder();
                        dbSql.Append("delete from consum_machine_cardtype ");
                        dbSql.AppendFormat(" where MachineId='{0}'", MachineEntity.MachineId);
                        await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                        await _db.Insertable(machineCardtypeList).ExecuteCommandAsync();
                        //关闭事务
                        _db.CommitTran();
                    }
                }
                catch (Exception ex)
                {
                    throw PARKException.Oh(ex.Message);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion
    }
}
